<template>
  <div class="page-container system-settings-container">
    <div class="d-flex justify-content-between align-items-center mb-4">
      <h2>系统设置</h2>
    </div>

    <div class="card">
      <div class="card-header">
        <h5 class="card-title mb-0">外观设置</h5>
      </div>
      <div class="card-body">
        <form @submit.prevent="saveSettings">
          <!-- 主题色设置 -->
          <div class="mb-4">
            <label class="form-label fw-bold">主题色设置</label>
            <div class="d-flex flex-wrap gap-3 mt-2">
              <div class="theme-option" :class="{ 'active': settings.theme === 'default' }" @click="selectTheme('default')">
                <div class="theme-preview default-theme">
                  <div class="theme-header"></div>
                  <div class="theme-body"></div>
                </div>
                <div class="theme-name">默认主题</div>
              </div>
              
              <div class="theme-option" :class="{ 'active': settings.theme === 'military' }" @click="selectTheme('military')">
                <div class="theme-preview military-theme">
                  <div class="theme-header"></div>
                  <div class="theme-body"></div>
                </div>
                <div class="theme-name">军绿主题</div>
              </div>
              
              <div class="theme-option" :class="{ 'active': settings.theme === 'redyellow' }" @click="selectTheme('redyellow')">
                <div class="theme-preview redyellow-theme">
                  <div class="theme-header"></div>
                  <div class="theme-body"></div>
                </div>
                <div class="theme-name">红黄主题</div>
              </div>
            </div>
          </div>

          <!-- 字体大小设置 -->
          <div class="mb-4">
            <label for="fontSize" class="form-label fw-bold">字体大小设置</label>
            <div class="row align-items-center mt-2">
              <div class="col-md-8">
                <input type="range" class="form-range" id="fontSize" min="12" max="20" step="1" v-model="settings.fontSize">
              </div>
              <div class="col-md-4">
                <div class="input-group">
                  <input type="number" class="form-control" min="12" max="20" v-model="settings.fontSize">
                  <span class="input-group-text">px</span>
                </div>
              </div>
            </div>
            <div class="mt-2">
              <p class="mb-0" :style="{ fontSize: settings.fontSize + 'px' }">预览文本大小效果</p>
            </div>
          </div>

          <div class="d-flex justify-content-end mt-4">
            <button type="button" class="btn btn-outline-secondary me-2" @click="resetSettings">
              <i class="bi bi-arrow-counterclockwise me-1"></i> 恢复默认
            </button>
            <button type="submit" class="btn btn-primary">
              <i class="bi bi-save me-1"></i> 保存设置
            </button>
          </div>
        </form>
      </div>
    </div>

    <div class="card mb-4">
      <div class="card-header">
        <h5 class="mb-0">数据库信息</h5>
      </div>
      <div class="card-body">
        <div class="mb-3">
          <label class="form-label">数据库存储位置</label>
          <div class="input-group">
            <input 
              type="text" 
              class="form-control" 
              v-model="dbPath" 
              readonly
            />
            <button 
              class="btn btn-outline-primary" 
              @click="backupDatabase"
            >
              备份数据库
            </button>
          </div>
          <div class="form-text">
            <span>数据库文件存储在固定位置，便于软件升级时保留数据</span>
          </div>
        </div>
        
        <div class="mb-3">
          <div class="d-flex align-items-center">
            <span class="me-2">管理员权限状态:</span>
            <span v-if="hasAdminRights" class="badge bg-success">已获取管理员权限</span>
            <span v-else class="badge bg-warning text-dark">未获取管理员权限</span>
          </div>
          <div class="form-text" v-if="!hasAdminRights">
            <i class="bi bi-exclamation-triangle-fill text-warning me-1"></i>
            建议以管理员身份运行本程序，以确保能够正常访问C盘根目录
          </div>
        </div>
        
        <div class="alert alert-info">
          <i class="bi bi-info-circle me-2"></i>
          <strong>数据迁移说明：</strong> 如需迁移数据，请将数据库文件复制到 C:\military_engineering_db 目录下。软件会自动连接到该位置的数据库文件。
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'

// 系统设置
const settings = ref({
  theme: 'military', // 默认为军绿主题
  fontSize: 14 // 默认字体大小 14px
})

// 数据库路径
const dbPath = ref('')
// 管理员权限状态
const hasAdminRights = ref(false)

// 选择主题
const selectTheme = (theme) => {
  settings.value.theme = theme
  applyTheme(theme)
}

// 应用主题
const applyTheme = (theme) => {
  try {
    console.log('开始应用主题:', theme);
    console.log('应用前body类列表:', document.body.classList);
    
    // 移除之前的主题类
    document.body.classList.remove('theme-default', 'theme-military', 'theme-redyellow');
    
    // 添加新主题类
    document.body.classList.add(`theme-${theme}`);
    
    console.log('应用后body类列表:', document.body.classList);
    
    // 更新侧边栏背景色
    const updateElementStyles = () => {
      const sidebar = document.querySelector('.sidebar');
      if (sidebar) {
        const style = getComputedStyle(document.body);
        const primaryDark = style.getPropertyValue('--primary-dark');
        console.log('应用侧边栏背景色:', primaryDark);
        sidebar.style.backgroundColor = primaryDark;
      }
    };

    // 立即更新一次
    updateElementStyles();
    
    // 100ms后再次更新，确保样式已完全加载
    setTimeout(updateElementStyles, 100);
    
  } catch (error) {
    console.error('应用主题出错:', error);
    alert('应用主题失败，请重试');
  }
}

// 重置设置
const resetSettings = () => {
  settings.value = {
    theme: 'military', // 重置为军绿主题
    fontSize: 14
  }
  applyTheme('military')
  document.documentElement.style.fontSize = '14px'
}

// 保存设置
const saveSettings = () => {
  // 这里应该是保存到本地存储或发送到服务器的逻辑
  localStorage.setItem('appSettings', JSON.stringify(settings.value))
  
  // 应用设置
  applyTheme(settings.value.theme)
  document.documentElement.style.fontSize = `${settings.value.fontSize}px`
  
  // 显示成功消息
  alert('设置已保存')
}

// 获取当前数据库路径和权限状态
async function getDbPath() {
  try {
    const result = await window.electronAPI.invoke('get-db-path')
    if (result.success) {
      dbPath.value = result.data
      
      // 直接检查管理员权限
      const adminResult = await window.electronAPI.invoke('check-admin-rights')
      if (adminResult.success) {
        hasAdminRights.value = adminResult.data
      }
    }
  } catch (error) {
    console.error('获取数据库路径失败:', error)
  }
}

// 备份数据库
async function backupDatabase() {
  try {
    const result = await window.electronAPI.invoke('backup-database')
    if (result.success) {
      // 显示成功消息
      alert(`数据库备份成功！\n备份文件位置: ${result.path}`)
    } else if (result.canceled) {
      // 用户取消了操作，不显示错误
    } else {
      alert(`备份失败: ${result.error}`)
    }
  } catch (error) {
    console.error('备份数据库失败:', error)
    alert(`备份失败: ${error.message}`)
  }
}

// 组件挂载时加载设置
onMounted(() => {
  // 从本地存储加载设置到组件状态，但不应用主题
  const savedSettings = localStorage.getItem('appSettings')
  if (savedSettings) {
    const parsedSettings = JSON.parse(savedSettings)
    settings.value = parsedSettings
  }
  
  // 只应用字体大小设置
  document.documentElement.style.fontSize = `${settings.value.fontSize}px`
  
  // 获取当前数据库路径和权限状态
  getDbPath()
})

// 移除组件卸载时的主题应用
onBeforeUnmount(() => {
  console.log('SystemSettings组件卸载')
})
</script>

<style scoped>
.theme-option {
  cursor: pointer;
  border: 2px solid #dee2e6;
  border-radius: 8px;
  padding: 8px;
  width: 150px;
  transition: all 0.2s;
}

.theme-option:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0,0,0,0.1);
}

.theme-option.active {
  border-color: #007bff;
  box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.25);
}

.theme-preview {
  height: 100px;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 8px;
}

.theme-header {
  height: 30%;
}

.theme-body {
  height: 70%;
}

.theme-name {
  text-align: center;
  font-weight: 500;
}

/* 默认主题预览 */
.default-theme .theme-header {
  background-color: #343a40;
}

.default-theme .theme-body {
  background-color: #f8f9fa;
}

/* 军绿主题预览 */
.military-theme .theme-header {
  background-color: #2d4f00;
}

.military-theme .theme-body {
  background-color: #f0f4e6;
}

/* 红黄主题预览 */
.redyellow-theme .theme-header {
  background-color: #c62828;
}

.redyellow-theme .theme-body {
  background-color: #fff9c4;
}
</style> 